package com.sian.security.web.authentication;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import com.sian.security.web.model.Authority;
import com.sian.security.web.model.Credential;
import com.sian.security.web.service.SecurityService;

@Service("authenticationProvider")
public class AuthenticationProviderImpl implements AuthenticationProvider
{
	@Autowired
	private SecurityService securityService;
	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException 
	{
		Credential credential = new Credential();
		credential.setJ_username((String) authentication.getPrincipal());
		credential.setJ_password((String) authentication.getCredentials());

		validate(credential);
		
		securityService.authenticate(credential);
		
		Collection<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
		
		List<Authority> authorityList = securityService.getAuthorities();
		for(Authority authority: authorityList)
		{
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getRoleName());
			grantedAuthorities.add(grantedAuthority);
		}
		
		return new UsernamePasswordAuthenticationToken(credential.getJ_username(),
				credential.getJ_password(),
                grantedAuthorities);
	}
	
	private void validate(Credential credential)
	{
		if(null != credential)
		{
			ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
			Validator validator = factory.getValidator();

			//Set<ConstraintViolation<Credential>> constraintViolations = validator.validate(credential);
		}
	}

	@Override
	public boolean supports(Class<?> auth)
	{
		if(UsernamePasswordAuthenticationToken.class.equals(auth))
		{
			return true;
		}

		return false;
	}

}
